﻿using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core;
using Castle.Facilities.FactorySupport;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
using MagickNet;
using MagickServer.Controllers;
using MagickServer.Services;
using MagickServer.Utils;
using MvcContrib.Castle;

namespace MagickServer {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication, IContainerAccessor {
        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            foreach (var r in ConfigurationManager.GetSection("routing") as IList<ImageRoute>) {
                routes.Add(r);
            }

            //routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{id}", // URL with parameters
            //    new {controller = "Home", action = "Index", id = ""} // Parameter defaults
            //    );
        }

        protected void Application_Start() {
            RegisterRoutes(RouteTable.Routes);
            InitializeWindsor();
            InitializeLog4Net();

            Magick.Init();
        }

        protected void InitializeLog4Net() {
            var appender = new FileAppender {
                File = "log.txt",
                Layout = new SimpleLayout(),
            };
            appender.ActivateOptions();
            BasicConfigurator.Configure(appender);
        }

        private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));

        /// <summary>
        /// Instantiate the container and add all Controllers that derive from 
        /// WindsorController to the container.  Also associate the Controller 
        /// with the WindsorContainer ControllerFactory.
        /// </summary>
        protected virtual void InitializeWindsor() {
            if (Container == null) {
                Container = new WindsorContainer();
                ComponentRegistrationExtensions.Kernel = Container.Kernel;

                Container.AddFacility<FactorySupportFacility>();

                ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));
                Container.Register(AllTypes.Of<Controller>().FromAssembly(typeof (ImageController).Assembly)
                                       .Configure(r => r.LifeStyle.Transient));

                Container.Register(Component.For<HttpServerUtilityFactory>());

                Container.Register(Component.For<HttpServerUtilityBase>()
                                       .FactoryMethod(k => k.Resolve<HttpServerUtilityFactory>().Create())
                                       .LifeStyle.Transient
                                       );

                Container.Register(Component.For<IImageSource>().ImplementedBy<VirtualFileImageSource>());
                //Container.Register(Component.For<IImageSource>().ImplementedBy<CachingImageSource>().DependsOn());
                Container.Register(Component.For<ICache>().ImplementedBy<CacheAdapter>());
            }
        }


        protected void Application_End() {}

        public IWindsorContainer Container { get; private set; }
    }
}